package com.access.boot.apisdk.param.resolve.argument;

import com.access.boot.apisdk.RequestContext;
import com.access.boot.apisdk.annotation.Param;
import com.access.boot.apisdk.annotation.ValueConstants;
import com.access.boot.apisdk.param.resolve.AbstractNamedValueMethodArgumentResolver;
import com.access.boot.apisdk.util.MethodParameter;

/**
 * @author YangZhen
 * @date 2022/6/26 14:43
 * @since 1.0.0
 */
public class RequestParamMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (parameter.hasParameterAnnotation(Param.class)) {
            return true;
        }
        return false;
    }

    @Override
    protected void resolveNamedValue(RequestContext httpRequest, String name, MethodParameter parameter, Object[] arguments) {
        Object argument = arguments[parameter.getParameterIndex()];
        String value = null;
        if (argument != null) {
            value = argument.toString();
        }
        httpRequest.addQueryParameter(name, value);
    }

    @Override
    protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
        Param ann = parameter.getParameterAnnotation(Param.class);
        return (ann != null ? new RequestParamNamedValueInfo(ann) : new RequestParamNamedValueInfo());
    }

    private static class RequestParamNamedValueInfo extends NamedValueInfo {

        public RequestParamNamedValueInfo() {
            super("", "", false, ValueConstants.DEFAULT_NONE);
        }

        public RequestParamNamedValueInfo(Param annotation) {
            super(annotation.name(), annotation.value(), annotation.required(), annotation.defaultValue());
        }
    }
}
